﻿using System;
using System.IO.Compression;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
	public class CompressAttribute : ActionFilterAttribute
	{
		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var request = filterContext.HttpContext.Request;

			var encodingHeader = request.Headers["Accept-Encoding"];

			if (string.IsNullOrEmpty(encodingHeader))
			{
				return;
			}

			encodingHeader = encodingHeader.ToLowerInvariant();

			var response = filterContext.HttpContext.Response;

			if (encodingHeader.Contains("gzip"))
			{
				response.AppendHeader("Content-encoding", "gzip");
				response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
			}
			else if (encodingHeader.Contains("deflate"))
			{
				response.AppendHeader("Content-encoding", "deflate");
				response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
			}
		}
	}
}